#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：pythonProject2 
@File    ：pro11.py
@Author  ：beibei
@Date    ：2023/12/19 4:40 PM 
'''
# """
# 爬虫作业：爬取lol英雄皮肤到本地
# 需求信息：
# 获取英雄联盟所有英雄信息
# url:'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?v=20'
# url结果返回有key：hero  这个key描述的是所有英雄信息和对应皮肤的列表
# 在hero列表中的元素，heroId描述的是英雄id，name指的英雄名
import requests
import os
import json

data_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))),
                         "data")
url = 'https://game.gtimg.cn/images/lol/act/img/js/heroList/hero_list.js?v=20'
output_file_path = data_path + '/hero_list.json'

try:
    response = requests.get(url)

    if response.status_code == 200:
        data = response.json()
        heroes = data.get('hero', [])
        hero_info = []
        for hero in heroes:
            hero_dict = {'heroId': hero['heroId'], 'name': hero['name']}
            hero_info.append(hero_dict)
    else:
        hero_info = "not case in file"

    with open(output_file_path, mode="w", encoding='utf-8') as output_file:
        json.dump(hero_info, output_file, ensure_ascii=False)

    print(f"已经写到文件夹中：{output_file_path}")
except Exception as e:
    print(f"An error occurred: {e}")

#
# 获取英雄数据以及皮肤信息url:'https://game.gtimg.cn/images/lol/act/img/js/hero/' + hero_id + '.js'
# 根据hero_id获取皮肤列表skins，每个皮肤都有皮肤名name和skinId，英雄有多少个皮肤他就有多少个skin

import os
import json


def find_hero_url(hero_id_search):
    try:
        script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
        file_path = os.path.join(script_dir, "data", "hero_list.json")

        # 从文件中读取 JSON 数据
        with open(file_path, 'r', encoding='utf-8') as file:
            hero_list = json.load(file)

        # 在英雄列表中查找指定 heroId 的英雄
        for hero in hero_list:
            if hero["heroId"] == hero_id_search:
                hero_url = f'https://game.gtimg.cn/images/lol/act/img/js/hero/{hero_id_search}.js'

                # 将 hero_url 写入到 hero_url.json 文件中
                output_file_path = os.path.join(script_dir, "data", "hero_url.json")
                with open(output_file_path, 'w', encoding='utf-8') as output_file:
                    json.dump({"hero_url": hero_url}, output_file, ensure_ascii=False, indent=4)

                return hero_url
    except Exception as e:
        print(f" {e}")
        return None

hero_url = find_hero_url("55")

# 获取英雄皮肤图：https://game.gtimg.cn/images/lol/act/img/skin/big1004.jpg
# 'big1004.jpg'的组成 'big'+{skinId} +'.jpg'
# ~~~~~~
import os
import json
import requests

# 读取 hero_url.json 文件中的 hero_url
def get_hero_url_from_file(file_path):
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
            return data.get("hero_url")
    except Exception as e:
        print(f"An error occurred while reading hero_url.json: {e}")
        return None

# 获取英雄 URL
# script_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))
# hero_url_json_path = os.path.join(script_dir, "data", "hero_url.json")
# hero_url = get_hero_url_from_file(hero_url_json_path)
#
# if hero_url:
#     try:
#         # 发送 HTTP GET 请求获取英雄数据
#         response = requests.get(hero_url)
#         response.raise_for_status()
#
#         # 解析 JSON 数据
#         data = response.json()
#
#         # 获取 skinid
#         skin_id = data.get("skin", {}).get("skinId")
#
#         if skin_id:
#             # 构建保存 skinid 的 JSON 数据
#             skin_data = {"skin_id": skin_id}
#
#
# else:
#     print("Failed to retrieve hero URL from hero_url.json.")



# 注：
# 1、储存英雄图片的方式可以用with open('xx.jpg', 'wb') as f: f.write(res.content)  res是接口请求的结果
# 2、文件夹名要根据英雄名来定义，一个文件夹只存储一个英雄的皮肤
# 3、python新建文件夹的方式（检索）
# 4、部分图片如果加载失败，需要用异常捕捉的方式跳过
# 5、如果遇到404 跳过
# """
#
# 结果截图1（代码截图）：
#
# 结果截图2（本地生成的效果）：
